package com.jdy.haoduoai.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.adapter.MyListDevicesAdapter;
import com.jdy.haoduoai.enums.SelectionMode;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.model.TeacherItem;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.widget.CustomCommonDialog;
import com.jdy.haoduoai.widget.CustomEditDialog;
import com.jdy.haoduoai.widget.PopWinShare;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

//import com.jdy.haoduoai.R;

@SuppressLint({"InflateParams", "HandlerLeak"})
public class AddTeacherListActivity extends BaseActivity implements OnClickListener {

    @InjectView(id = R.id.listview_devices)
    private ListView listview_devices;
    @InjectView(id = R.id.bottomlyt)
    private LinearLayout bottomlyts;
    @InjectView(id = R.id.delete, click = true)
    private Button delete;
    @InjectView(id = R.id.select, click = true)
    private Button select;

    private MyListDevicesAdapter mMyListDevicesAdapter;

    @Override
    @SuppressLint("InflateParams")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        setContentView(R.layout.teacherlist);

        mTitleText.setTextColor(0xff000000);
        setTitle("宝宝的老师");

        initUpRightBtn();

        loadBindedTeacherList();
    }

    PopWinShare popWinShare;

    private void initUpRightBtn() {
        mBackImageButton.setImageResource(R.drawable.black_back);
        titleLayout.setBackgroundColor(0xffffffff);

//    img_upright.setVisibility(View.VISIBLE);
//    img_upright.setImageResource(R.drawable.add_habit_icon);
//    img_upright.setOnClickListener(new OnClickListener() {
//      @Override
//      public void onClick(View v) {
//
//
//          if (bottomlyts.isShown()) {
//            bottomlyts.setVisibility(View.GONE);
//            img_upright.setImageResource(R.drawable.add_habit_icon);
//            if ( mMyListDevicesAdapter != null) {
//              mMyListDevicesAdapter.setEditor(false);
//              mMyListDevicesAdapter.notifyDataSetChanged();
//
//              if (mTeacherItemList != null) {
//                for (TeacherItem item : mTeacherItemList) {
//                  item.isChecked = false;
//                }
//              }
//            }
////            if (currIndex == 1 && mCustomPainPointAdapter != null) {
////              mCustomPainPointAdapter.setEditor(false);
////
////              if (mRadioArrayList != null) {
////                for (PainPointItem item : mRadioArrayList) {
////                  item.isChecked = false;
////                }
////              }
////              // mCustomPainPointAdapter.setData(mRadioArrayList);
////
////              if (mCustomPainPointAdapter.getCount() == 0) {
////                emptylayout2.setVisibility(View.VISIBLE);
////                btnReload2.setVisibility(View.GONE);
////                img_defaultfail2.setBackgroundResource(R.drawable.empty_mylove);
////              } else {
////                emptylayout2.setVisibility(View.GONE);
////              }
////
////              mCustomPainPointAdapter.notifyDataSetChanged();
////            }
//
////            toplyt.setVisibility(View.VISIBLE);
////            bealyt.setVisibility(View.VISIBLE);
//            getbtn_right().setBackgroundResource(R.drawable.edit_btn);
//            mBackImageButton.setVisibility(View.VISIBLE);
//          } else {
//            if (popWinShare == null) {
//              OnClickLintener paramOnClickListener = new OnClickLintener();
//              popWinShare = new PopWinShare(AddTeacherListActivity.this, paramOnClickListener, Tools.getPixelByDip(AddTeacherListActivity.this,160), Tools.getPixelByDip(AddTeacherListActivity.this,160));
//              popWinShare.getContentView().setOnFocusChangeListener(new View.OnFocusChangeListener() {
//
//                @Override
//                public void onFocusChange(View v, boolean hasFocus) {
//                  if (!hasFocus) {
//                    popWinShare.dismiss();
//                  }
//                }
//              });
//            }
//
//            popWinShare.setTextTeacher();
//            popWinShare.setFocusable(true);
//            popWinShare.showAsDropDown(img_upright, 0, 0);
//            popWinShare.update();
//          }
//
//
//
//
//      }
//    });
    }

    private void bindTeacher(final String teacherTel, final String bindCode, final DialogInterface dialog) {
        new CustomAsyncTask(this, new IAsyncTask() {
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                if (result.isSuccess() && Tools.isNotNullStr(result.data)) {
//          ArrayList<PainPointItem> list = (ArrayList<PainPointItem>) JsonSerializer
//                  .getInstance().deserialize(result.data, ArrayList.class,
//                          PainPointItem.class);
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    loadBindedTeacherList();
                } else {
                    if (Tools.isNotNullStr(result.data)) {
                        toastShow(result.data);
                    }
                }

            }

            @Override
            public ResponseResult doInbackground(Activity activity) {
                HashMap<String, Object> param_ = new HashMap<String, Object>();

                if (mGlobalLeUser != null) {
                    param_.put(HttpUtils.TAG_SNO_I, mGlobalLeUser.sno);
                } else {
                    LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
                    if (lu == null) {
                        lu = Tools.restoreLeUser();
                    }
                    param_.put(HttpUtils.TAG_SNO_I, lu.sno);
                }
                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
                param_.put("teacher_id", teacherTel);
                param_.put("code", bindCode);

                return HttpUtils.startRequest(HttpUtils.API_URL + "/api/2.0/teacher/teacher_machine/bind_teacher_bycode", param_,
                        HttpUtils.TAG_POST_REQUEST);
            }
        }).execute();
    }

    ArrayList<TeacherItem> mTeacherItemList;

    private void loadBindedTeacherList() {
        new CustomAsyncTask(this, new IAsyncTask() {
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                if (result.isSuccess() && Tools.isNotNullStr(result.data)) {
                    mTeacherItemList = (ArrayList<TeacherItem>) JsonSerializer
                            .getInstance().deserialize(result.data, ArrayList.class,
                                    TeacherItem.class);

                    if (mTeacherItemList != null) {
                        if (mMyListDevicesAdapter == null) {
                            mMyListDevicesAdapter = new MyListDevicesAdapter(AddTeacherListActivity.this, mTeacherItemList);
                        } else {
                            mMyListDevicesAdapter.updateData(mTeacherItemList);
                        }

                        listview_devices.setAdapter(mMyListDevicesAdapter);
                        mMyListDevicesAdapter.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {
                HashMap<String, Object> param_ = new HashMap<String, Object>();

                if (mGlobalLeUser != null) {
                    param_.put(HttpUtils.TAG_SNO_I, mGlobalLeUser.sno);
                } else {
                    LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
                    if (lu == null) {
                        lu = Tools.restoreLeUser();
                    }
                    param_.put(HttpUtils.TAG_SNO_I, lu.sno);
                }

                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
                param_.put("page", 1);

                return HttpUtils.startRequest(HttpUtils.API_URL + "/api/2.0/teacher/teacher_machine/bind_teacher_list", param_,
                        HttpUtils.TAG_GET_REQUEST);
            }
        }).execute();
    }

    class OnClickLintener implements OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.layout_addhabit:
                    //    startActivity(new Intent(MyPainPointSelectActivity.this, AddHabitClockActivity.class));
                    // startActivityForResult(new Intent(this, AddHabitClockActivity.class), 100);
                    //   bindTeacher("13521323795", "123456");

                    if (popWinShare != null) {
                        popWinShare.dismiss();
                    }

                    final CustomEditDialog.Builder customBuilder = new CustomEditDialog.Builder(AddTeacherListActivity.this);
                    customBuilder.setTitle("请输入绑定老师信息")
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String tel = customBuilder.getEditText();
                            String bindCode = customBuilder.getEditText2();
                            if (Tools.isNotEmpty(tel) && Tools.isNotEmpty(bindCode)) {
                                bindTeacher(tel, bindCode, dialog);
                            } else {
                                toastShow("绑定信息不能为空!");
                            }
                        }
                    });

                    if (!isFinishing()) {
                        customBuilder.create().show();
                    }

                    break;
                case R.id.layout_edithabit:
                    popWinShare.dismiss();

                    if (!bottomlyts.isShown()) {
                        bottomlyts.setVisibility(View.VISIBLE);
                        img_upright.setImageResource(R.drawable.cancle);
                        mMyListDevicesAdapter.setEditor(true);
                        mMyListDevicesAdapter.notifyDataSetChanged();
                        //    mCommitBtn.setVisibility(View.GONE);
//            vpager.setScanScroll(false);
//            if (currIndex == 1 && mCustomPainPointAdapter != null) {
//              mCustomPainPointAdapter.setEditor(true);
//              mCustomPainPointAdapter.notifyDataSetChanged();
//            }

//            toplyt.setVisibility(View.GONE);
//            bealyt.setVisibility(View.GONE);
                        mBackImageButton.setVisibility(View.INVISIBLE);
                    } else {
                        bottomlyts.setVisibility(View.GONE);
                        //   mCommitBtn.setVisibility(View.VISIBLE);
                        //  vpager.setScanScroll(true);
                        img_upright.setImageResource(R.drawable.add_habit_icon);

                        if (mMyListDevicesAdapter != null) {
                            mMyListDevicesAdapter.setEditor(false);
                            mMyListDevicesAdapter.notifyDataSetChanged();

                            if (mTeacherItemList != null) {
                                for (TeacherItem item : mTeacherItemList) {
                                    item.isChecked = false;
                                }
                            }
                        }

//            if (currIndex == 1 && mCustomPainPointAdapter != null) {
//              mCustomPainPointAdapter.setEditor(false);
//
//              if (mRadioArrayList != null) {
//                for (PainPointItem item : mRadioArrayList) {
//                  item.isChecked = false;
//                }
//              }
//              mCustomPainPointAdapter.notifyDataSetChanged();
//            }

//            toplyt.setVisibility(View.VISIBLE);
//            bealyt.setVisibility(View.VISIBLE);
                        getbtn_right().setBackgroundResource(R.drawable.edit_btn);
                        mBackImageButton.setVisibility(View.VISIBLE);
                    }

                    break;

                default:
                    break;
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.delete:
                deleteTeacher();
                break;
            case R.id.select:
                if (select.getText().toString().equals("全选")) {
                    if (mMyListDevicesAdapter != null) {
                        mMyListDevicesAdapter.setSelectMode(SelectionMode.SELECT_ALL);
                        mMyListDevicesAdapter.notifyDataSetChanged();
                    }

                    select.setText("取消全选");
                } else if (select.getText().toString().equals("取消全选")) {
                    if (mMyListDevicesAdapter != null) {
                        mMyListDevicesAdapter.setSelectMode(SelectionMode.DESELECT_ALL);
                        mMyListDevicesAdapter.notifyDataSetChanged();
                    }

                    select.setText("全选");
                }
                break;

            default:
                break;
        }
    }

    private void deleteTeacher() {
        int selectCount = 0;
        if (mTeacherItemList != null) {
            for (TeacherItem item : mTeacherItemList) {
                if (item != null && item.isChecked) {
                    ++selectCount;
                }
            }
        }

        if (selectCount > 0) {
            CustomCommonDialog.Builder cdb = new CustomCommonDialog.Builder(this).setMessage("确定删除吗？").setTitle("删除提示")
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id) {

                            if (mTeacherItemList != null && !mTeacherItemList.isEmpty()) {
                                final List<TeacherItem> selectedRecordings = new ArrayList<TeacherItem>();
                                String storyIds = "";

                                for (TeacherItem item : mTeacherItemList) {
                                    if (item.isChecked) {
                                        selectedRecordings.add(item);
                                        storyIds += item.id;
                                        storyIds += ",";
                                    }
                                }

                                if (Tools.isNotEmpty(storyIds)) {
                                    storyIds = storyIds.substring(0, storyIds.length() - 1);
                                }

                                if (selectedRecordings.size() > 0) {
                                    //showloading("");
                                    final String finalStoryIds = storyIds;
                                    new CustomAsyncTask(AddTeacherListActivity.this,
                                            new IAsyncTask() {
                                                @Override
                                                public void onRecieveData(Activity activity,
                                                                          ResponseResult result) {

                                                    for (TeacherItem rItem : selectedRecordings) {
                                                        mMyListDevicesAdapter.remove(rItem);
                                                    }
                                                    mMyListDevicesAdapter.removeSelection();

                                                    if (Tools.isNotNullStr(result.data)) {
                                                        Toast.makeText(AddTeacherListActivity.this, result.data, Toast.LENGTH_SHORT).show();
                                                    }

                                                }

                                                @Override
                                                public ResponseResult doInbackground(Activity activity) {
                                                    LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
                                                    if (lu == null) {
                                                        lu = Tools.restoreLeUser();
                                                    }

                                                    HashMap<String, Object> param_ = new HashMap<String, Object>();
                                                    param_.put(HttpUtils.TAG_SNO_I, lu.sno);
                                                    param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
                                                    return HttpUtils.startRequest(HttpUtils.HOST_API
                                                                    + "/api/2.0/teacher/teacher_machine/bind_teacher_destroy/" + finalStoryIds,
                                                            param_, HttpUtils.TAG_DELETE_REQUEST);
                                                }
                                            }).execute();

                                }
                                dialog.dismiss();
                            }
                        }
                    });
            cdb.create().show();
        } else {
            Toast.makeText(AddTeacherListActivity.this, "未选中任何条目!", Toast.LENGTH_SHORT).show();
        }
    }

}
